import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:sml_policies/locator/locator.dart';
import 'package:sml_policies/locator/sml_policies.dart';
import 'package:sml_policies/ui/webview/webview_common.dart';
import 'package:sml_policies/ui/widgets/app_button.dart';
import 'package:permission_handler/permission_handler.dart';

import 'animate.dart';
import 'exit_confirm_dialog.dart';

class PermissionsDialog extends Dialog {
  const PermissionsDialog({super.key});

  @override
  Widget build(BuildContext context) {
    return const PermissionDialogContent();
  }

  Future show(BuildContext context) async {
    await showAnimDialog(context, const PermissionsDialog());
  }

}

class PermissionDialogContent extends StatefulWidget {
  const PermissionDialogContent({Key? key}) : super(key: key);

  @override
  State<PermissionDialogContent> createState() => _PermissionDialogContentState();
}

class _PermissionDialogContentState extends State<PermissionDialogContent> {

  final SmlPoliciesConfig smlPoliciesConfig = locator<SmlPoliciesConfig>();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: WillPopScope(
        child: Container(
          margin: EdgeInsets.only(top: 80.h),
          // width: 200,
          // height: 200,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(24.0)),
            color: Color(0xFF362C4C),
          ),
          child: Column(
            children: [
              topOfDialog(),
              SizedBox(height: 10.h),
              Expanded(
                  child: Container(
                    padding: EdgeInsets.only(left: 15.w, right: 15.w,
                        bottom: 15.h),
                    child: Column(
                      children: [
                        // header(),
                        Expanded(
                            child: Container(
                              decoration: const BoxDecoration(
                                  color: Color(0xFFE4F5E6),
                                  borderRadius: BorderRadius.all(Radius.circular(8))
                              ),
                              child: permissionsList(),
                            )
                        ),
                        SizedBox(height: 15.h),
                        btnGroup(context)
                      ],
                    ),
                  )
              )
            ],
          ),
        ),
        onWillPop: () async {
          return false;
        }
      ),
    );
  }

  Widget topOfDialog() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 15.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(height: 10.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                smlPoliciesConfig.languageMap['permissionTitle'].toString(),
                style: const TextStyle(fontSize: 30, color: Colors.white, fontWeight: FontWeight.bold)
              ),
              // Container(
              //   width: 102.r,
              //   height: 102.r,
              //   child: Image.asset("images/permission_head_bg.png", fit: BoxFit.contain),
              //   // child: "logo".assetsImg(width: 60.r, height: 60.r),
              // ),
            ],
          ),
          SizedBox(height: 10.h),

          SizedBox(height: 10.h),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
            decoration: const BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(5)),
              color: Colors.white
            ),
            child: Text(smlPoliciesConfig.languageMap['permissionHeader'].toString(),
                style: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold)),
          )
        ],
      ),
    );
  }

  Widget btnGroup(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child: AppButton(
            height: 40.h,
            // outline: true,
            content: smlPoliciesConfig.languageMap['deny'],
            style: const TextStyle(color: Colors.white),
            // radius: 90,
            color: Colors.grey,
            onTap: () {
              reject();
            },
          ),
        ),
        SizedBox(width: 10.w),
        Expanded(
            child: AppButton(
              height: 40.h,
              lightTheme: false,
              content: smlPoliciesConfig.languageMap['agree'],
              style: const TextStyle(color: Colors.white),
              // radius: 5,
              onTap: () {
                agree();
              },
            )
        )
      ],
    );
  }

  Widget permissionsList() {
    return CommonWebView(
      url: locator<SmlPoliciesConfig>().permissionUrl ?? '',
      onClosePop: () {
        agree();
      },
    );
  }

  void reject() {
    smlPoliciesConfig.logEvent("loginphone-permission-click-deny");

    ExitConfirmDialog(
      onConfirm: () {
        smlPoliciesConfig.logEvent("loginphone-permission-exit");
        SystemNavigator.pop();
        // exit(0);
      },
    ).show(context);
  }

  void agree() async {
    smlPoliciesConfig.logEvent("loginphone-permission-click-agree");

    List<Permission> pers = [
      Permission.phone,
      Permission.camera,
      Permission.location,
      Permission.sms,
      Permission.calendar
    ];

    Map<Permission, PermissionStatus> status = await pers.request();
    debugPrint('status: $status');

    Map statusRes = await getPermissionStatus(pers);
    debugPrint('statusRes: $statusRes');

    if (statusRes['permanentlyDenied'] || (statusRes['permanentlyDenied'] == false) && statusRes['allAgree'] == false) {
      smlPoliciesConfig.onToast(smlPoliciesConfig.languageMap['permissionObtain']);
      return;
    }

    if (statusRes['allAgree']) {
      smlPoliciesConfig.logEvent("loginphone-permission-agree-success");
      Navigator.pop(context);

      // ScrollBottomListenDialog(url: '${AppConfig().baseH5Url}/privacy_policy').show(context);
    }
  }

  getPermissionStatus(List<Permission> pers) async {
    Map statusRes = {
      "allAgree": true,
      "permanentlyDenied": false
    };

    for (var element in pers) {
      PermissionStatus status = await element.status;
      if (status.isGranted) {
        smlPoliciesConfig.logEvent("loginphone-permission-$element-yes");
        // statusRes['allAgree'] = true;
      } else if (status.isDenied) {
        statusRes['allAgree'] = false;
        smlPoliciesConfig.logEvent("loginphone-permission-$element-no");
      } else {
        statusRes['permanentlyDenied'] = true;
        smlPoliciesConfig.logEvent("loginphone-permission-$element-no");
      }

    }

    return statusRes;
  }

}

